package chapter6;

import java.io.IOException;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;


import chapter1.InstallBouncyCastle;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v1CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.x509.X509V1CertificateGenerator;

import javax.security.auth.x500.X500Principal;


/**
 * Basic X.509 V1 Certificate creation.
 */
public class X509V1CreateExample extends InstallBouncyCastle {

    /**
     * 不建议使用V1证书了
     *
     * @param keyPair
     * @return
     * @throws IOException
     * @throws OperatorCreationException
     * @throws CertificateException
     */
    public static X509Certificate generateV1Cert(KeyPair keyPair) throws IOException, OperatorCreationException, CertificateException {
        // dump public key
        ASN1InputStream aIn = new ASN1InputStream(keyPair.getPublic().getEncoded());
        SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(aIn.readObject());

        X509v1CertificateBuilder v1CertificateBuilder = new X509v1CertificateBuilder(new X500Name("CN=Ainge CA Certificate"),
                BigInteger.valueOf(System.currentTimeMillis()), new Date(System.currentTimeMillis() - 50000), new Date(System.currentTimeMillis() + 50000),
                new X500Name("CN=Sub CA Certificate"), subjectPublicKeyInfo);

        //  create simple signer
        ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(keyPair.getPrivate());

        X509CertificateHolder holder = v1CertificateBuilder.build(signer);

        X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(holder);

        return certificate;
    }


    //  过期的实现
    public static X509Certificate generateV1Certificate(KeyPair pair)
            throws Exception {
        // generate the certificate
        X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
        certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
        certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
        certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
        certGen.setPublicKey(pair.getPublic());
        certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
        return certGen.generateX509Certificate(pair.getPrivate(), "BC");
    }

    public static void main(String[] args) throws Exception {
        // create the keys
        KeyPair pair = Utils.generateRSAKeyPair();
        // generate the certificate
        // X509Certificate cert = generateV1Certificate(pair);
        X509Certificate cert = generateV1Cert(pair);
        // show some basic validation
        cert.checkValidity(new Date());

        cert.verify(cert.getPublicKey());
        System.out.println("valid certificate generated");
    }
}
